<template>
  <div class="analysis-container">
    <!-- 图表容器 -->
    <div class="charts-grid">
      <!-- 雷达图 -->
      <div class="chart-card animate-fade-in-up" style="animation-delay: 0.1s">
        <div class="chart-header">
          <h3 class="chart-title">多维度能力值分布</h3>
          <div class="chart-subtitle">症状意义</div>
        </div>
        <div class="chart-content">
          <Echart :options="radarOptions" :height="400" />
        </div>
      </div>

      <!-- 趋势图 -->
      <div class="chart-card animate-fade-in-up" style="animation-delay: 0.2s">
        <div class="chart-header">
          <h3 class="chart-title">多维度能力值趋势</h3>
        </div>
        <div class="chart-content">
          <Echart :options="trendOptions" :height="400" />
        </div>
      </div>

      <!-- 排名图 -->
      <div class="chart-card animate-fade-in-up" style="animation-delay: 0.3s">
        <div class="chart-header">
          <h3 class="chart-title">多维度能力值排名</h3>
        </div>
        <div class="chart-content">
          <Echart :options="rankingOptions" :height="400" />
        </div>
        <div class="dimension-tabs center">
          <button
            v-for="dim in availableDimensions"
            :key="dim"
            class="tab-button"
            :class="{ active: activeDimension === dim }"
            @click="switchDimension(dim as string)"
          >
            {{ dim }}
          </button>
        </div>
        <div class="user-info" v-if="userInfo">
          <span class="info-item">当前用户: <strong>{{ userInfo.name }}</strong></span>
          <span class="info-item">分数: <strong>{{ userInfo.score }}</strong></span>
          <span class="info-item">排名: <strong>{{ userInfo.rank }}</strong></span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Echart } from '@/components/Echart'
import * as AnalysisApi from '@/api/dt/userexam'
import { useUserStore } from '@/store/modules/user'
import { useRoute } from 'vue-router'

defineOptions({ name: 'DtUserExam' })

const userStore = useUserStore()
const jobId = ref<number | String>('')
// 使用封装的 Echart 组件，不再需要手工实例与 ref

// 数据状态
const radarData = ref<any>(null)
const trendData = ref<any>(null)
const rankingData = ref<any>(null)
const activeDimension = ref('')

// 用户信息
const userInfo = ref({
  name: '',
  score: '',
  rank: ''
})

// 更新用户信息
const updateUserInfo = () => {
  const list = rankingData.value || []
  const currentDim = list.find((d: any) => d.dimension === activeDimension.value) || list[0]
  const dataList = (currentDim?.dataList || []) as any[]
  const currentUserData = dataList.find((item: any) => item.isCurrentUser) || dataList[0]

  if (currentUserData) {
    userInfo.value = {
      name: currentUserData.nickName || '用户',
      score: currentUserData.userScore || '0.000',
      rank: `${currentUserData.rank ?? (dataList.findIndex((i) => i === currentUserData) + 1)}/${dataList.length}`
    }
  } else {
    userInfo.value = { name: '', score: '', rank: '' }
  }
}

watch(
  () => activeDimension.value,
  () => {
    updateUserInfo()
  }
)

// 计算 Echart 配置项
const radarOptions = computed(() => {
  const radarDataList = radarData.value || []
  const scores = radarDataList.map((item: any) => Number(item.score) || 0)
  const maxScore = scores.length ? Math.max(...scores) : 1
  const minScore = scores.length ? Math.min(...scores) : 0
  
  // 确保雷达图范围包含所有数据点，包括负数
  const range = Math.max(Math.abs(maxScore), Math.abs(minScore))
  const paddedRange = range === 0 ? 1 : range * 1.2
  
  const indicators = radarDataList.map((item: any) => ({ 
    name: item.dimension, 
    max: paddedRange, 
    min: -paddedRange 
  }))
  const values = scores
  return {
    backgroundColor: 'transparent',
    tooltip: { trigger: 'item' },
    radar: {
      indicator:
        indicators.length > 0
          ? indicators
          : [
              { name: '症状意义', max: 1, min: 0 },
              { name: '症状影响', max: 1, min: 0 }
            ],
      shape: 'circle',
      center: ['50%', '50%'],
      radius: '75%'
    },
    series: [
      {
        type: 'radar',
        data: [
          {
            value: values.length > 0 ? values : [0, 0],
            name: '能力值',
            areaStyle: { color: 'rgba(34, 197, 94, 0.25)' },
            lineStyle: { color: '#22c55e', width: 2 },
            itemStyle: { color: '#22c55e' }
          }
        ]
      }
    ]
  }
})

const trendOptions = computed(() => {
  const trendDataList = trendData.value || []
  const allTimesSet = new Set<string>()
  const toLabel = (t: number) => {
    const d = new Date(t)
    const mm = d.getMonth() + 1
    const dd = d.getDate()
    const HH = d.getHours().toString().padStart(2, '0')
    const MM = d.getMinutes().toString().padStart(2, '0')
    return `${mm}/${dd} ${HH}:${MM}`
  }
  const timeValueMapList: { name: string; map: Record<string, number> }[] = []
  trendDataList.forEach((dimensionData: any) => {
    const name = dimensionData.dimension
    const map: Record<string, number> = {}
    ;(dimensionData.dataList || []).forEach((item: any) => {
      const t = item.time ?? item.create_time
      const label = toLabel(Number(t))
      allTimesSet.add(label)
      const s = Number(item.score) || 0
      map[label] = s
    })
    timeValueMapList.push({ name, map })
  })
  const categories = Array.from(allTimesSet).sort((a, b) => new Date(a).getTime() - new Date(b).getTime())
  const seriesData = timeValueMapList.map(({ name, map }) => ({ name, type: 'line', smooth: true, data: categories.map((c) => (map[c] ?? null)) }))
  return {
    backgroundColor: 'transparent',
    tooltip: { trigger: 'axis' },
    legend: { data: seriesData.map((s: any) => s.name), top: '5%', right: '5%' },
    xAxis: { type: 'category', data: categories.length > 0 ? categories : ['暂无'] },
    yAxis: { type: 'value' },
    series: seriesData.length > 0 ? seriesData : [{ name: '暂无', type: 'line', data: [0] }]
  }
})

const rankingOptions = computed(() => {
  const list = rankingData.value || []
  const current = list.find((d: any) => d.dimension === activeDimension.value) || list[0]
  const dataList = (current?.dataList || []) as any[]
  const sorted = dataList
    .map((i) => ({ name: i.nickName || '用户', score: Number(i.userScore) || 0 }))
    .sort((a, b) => b.score - a.score)
  const categories = sorted.map((i) => i.name)
  const values = sorted.map((i) => i.score)
  return {
    backgroundColor: 'transparent',
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    xAxis: { type: 'category', data: categories.length ? categories : ['暂无'] },
    yAxis: { type: 'value' },
    series: [
      { name: activeDimension.value || current?.dimension || '维度', type: 'bar', data: values.length ? values : [0], label: { show: true, position: 'top', formatter: ({ value }: any) => (value == null ? '' : String(value)) } }
    ]
  }
})

const switchDimension = (dimension: string) => {
  activeDimension.value = dimension
}

const availableDimensions = computed(() => {
  const list = rankingData.value || []
  const dims = list.map((d: any) => d.dimension).filter(Boolean)
  return dims
})

watch(
  () => availableDimensions.value,
  (dims) => {
    if (!activeDimension.value && dims?.length) activeDimension.value = dims[0]
  },
  { immediate: true }
)

// 加载数据
const loadData = async () => {
  try {
    const [radarRes, trendRes, rankingRes] = await Promise.all([
      AnalysisApi.getRadarData({ jobId: jobId.value, userId: userStore.user?.id }),
      AnalysisApi.getTrendData({ jobId: jobId.value, userId: userStore.user?.id }),
      AnalysisApi.getRankingData({ jobId: jobId.value, userId: userStore.user?.id })
    ])
    radarData.value = radarRes
    trendData.value = trendRes
    rankingData.value = rankingRes
    // 仅从真实返回的第一个维度设置默认
    if (!activeDimension.value) {
      const dims = (rankingRes || []).map((d: any) => d?.dimension).filter(Boolean)
      if (dims.length) activeDimension.value = dims[0]
    }
    updateUserInfo()
  } catch (error) {
    console.error('加载数据失败，使用默认数据:', error)
  }
}

onMounted(() => {
  const route = useRoute()
  if (route.query.jobId) jobId.value = String(route.query.jobId)
  loadData()
})

onUnmounted(() => {})
</script>

<style scoped>
* {
  box-sizing: border-box;
}
.analysis-container {
  padding: 16px;
  min-height: 100vh;
  width: 100%;
  max-width: 100vw;
  overflow-x: hidden;
  box-sizing: border-box;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 32px;
  font-weight: 700;
  color: #1e293b;
  margin-bottom: 8px;
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-subtitle {
  font-size: 16px;
  color: #64748b;
  margin: 0;
}

.charts-grid {
  display: flex;
  flex-direction: column;
  gap: 24px;
  margin-bottom: 32px;
}

.chart-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow:
    0 4px 6px -1px rgba(0, 0, 0, 0.1),
    0 2px 4px -1px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  border: 1px solid rgba(226, 232, 240, 0.8);
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.chart-card:hover {
  transform: translateY(-4px);
  box-shadow:
    0 20px 25px -5px rgba(0, 0, 0, 0.1),
    0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

.chart-header {
  margin-bottom: 20px;
}

.chart-title {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 8px 0;
  text-align: center;
}

.chart-subtitle {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
  text-align: center;
}

.chart-content {
  position: relative;
  padding: 5px;
  overflow: hidden;
}

.chart-container {
  width: 100%;
  height: 400px;
  max-width: 100%;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;
}

.footer-info {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow:
    0 4px 6px -1px rgba(0, 0, 0, 0.1),
    0 2px 4px -1px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(226, 232, 240, 0.8);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.dimension-tabs {
  display: flex;
  gap: 8px;
}

.dimension-tabs.center {
  justify-content: center;
  margin-bottom: 16px;
}

.tab-button {
  padding: 8px 16px;
  border-radius: 8px;
  border: none;
  background: #f1f5f9;
  color: #64748b;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.tab-button:hover {
  background: #e2e8f0;
}

.tab-button.active {
  background: #0ea5e9;
  color: white;
}

.user-info {
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
  justify-content: center;
}

.info-item {
  font-size: 14px;
  color: #64748b;
}

.info-item strong {
  color: #1e293b;
  font-weight: 600;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fade-in-up {
  animation: fadeInUp 0.6s ease-out forwards;
  opacity: 0;
}

@media (max-width: 768px) {
  .analysis-container {
    padding: 16px;
  }

  .page-title {
    font-size: 24px;
  }

  .chart-card {
    padding: 16px;
  }

  .chart-container {
    height: 250px;
  }

  .footer-info {
    flex-direction: column;
    align-items: flex-start;
  }

  .user-info {
    gap: 16px;
  }
}
</style>
